package com.gnss.common.utils;

import com.gnss.common.proto.TerminalProto;
import org.springframework.data.redis.core.HashOperations;

import java.util.Map;
import java.util.Objects;

/**
 * @author guangbinhuang
 * @date 2018/11/5
 * @desc Redis工具
 **/
public class RedisUtil {

    private RedisUtil() {
    }

    /**
     * Redis在线终端缓存Key
     */
    private static final String TERMINAL_ONLINE_REDIS_KEY = "terminal-online";

    /**
     * 缓存在线终端
     * @param terminalHashOperations
     * @param terminalInfo
     */
    public static void putOnlineTerminal(HashOperations<String, String, TerminalProto> terminalHashOperations, TerminalProto terminalInfo) {
        terminalHashOperations.put(TERMINAL_ONLINE_REDIS_KEY, String.valueOf(terminalInfo.getTerminalId()), terminalInfo);
    }

    /**
     * 获取在线终端
     * @param terminalHashOperations
     * @param terminalId
     * @return
     */
    public static TerminalProto getOnlineTerminal(HashOperations<String, String, TerminalProto> terminalHashOperations, Long terminalId) {
        return terminalHashOperations.get(TERMINAL_ONLINE_REDIS_KEY, String.valueOf(terminalId));
    }

    /**
     * 删除在线终端
     * @param terminalHashOperations
     * @param terminalInfo
     */
    public static void deleteOnlineTerminal(HashOperations<String, String, TerminalProto> terminalHashOperations, TerminalProto terminalInfo) {
        terminalHashOperations.delete(TERMINAL_ONLINE_REDIS_KEY, String.valueOf(terminalInfo.getTerminalId()));
    }

    /**
     * 删除某个节点的所有在线终端
     * @param terminalHashOperations
     * @param nodeName
     */
    public static void deleteAllOnlineTerminals(HashOperations<String, String, TerminalProto> terminalHashOperations, String nodeName) {
        Map<String, TerminalProto> map = terminalHashOperations.entries(TERMINAL_ONLINE_REDIS_KEY);
        map.forEach((k, v) -> {
            if (Objects.equals(nodeName, v.getNodeName())) {
                terminalHashOperations.delete(TERMINAL_ONLINE_REDIS_KEY, k);
            }
        });
    }

}
